﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DebugInfoViewer
{
	
	public class DebugInfo
	{
		private class DebugInfoObject
		{
			public DebugInfoObject(TreeNode p_node, string p_info)
			{
				m_node = p_node;
				m_node.Nodes.Add(p_info);
			}
			public void updateInfo(string p_name, string p_info)
			{
				m_counter++;
				if(m_counter > 30)
				{
					m_node.Nodes[0].Text = p_info;
					m_counter = 0;
				}
				m_node.Text = p_name + ": " + p_info;
			}
			private readonly TreeNode m_node;
			private int m_counter = 0;
		}
		public DebugInfo(TreeNode p_node, string p_name, string p_info)
		{
			m_node = p_node;
			m_infoMapping = new Dictionary<string, DebugInfoObject>();
			m_infoMapping[p_name] = new DebugInfoObject(m_node.Nodes.Add(p_info), p_info);
		}
		public void updateInfo(string p_name, string p_info)
		{
			if(m_infoMapping.ContainsKey(p_name))
			{
				m_infoMapping[p_name].updateInfo(p_name, p_info);
			}
			else
			{
				m_infoMapping[p_name] = new DebugInfoObject(m_node.Nodes.Add(p_name + ": " + p_info), p_info);
			}
		}
		private readonly TreeNode m_node;
		private readonly Dictionary<string, DebugInfoObject> m_infoMapping;
	}

	static public class DebugMain
	{
		static DebugForm m_form;
		private static bool m_open;
		private static Dictionary<WeakReference, DebugInfo> m_debugList = new Dictionary<WeakReference, DebugInfo>();

		static DebugMain()
		{
			m_form = new DebugForm();
			m_form.Show();
			m_open = true;
			m_form.FormClosed += delegate { m_open = false; };
		}

		static public void ShowDebugInfo(string p_name, string p_info, Object p_object)
		{
			// don't add when the debug window is closed
			if(m_open == false) return;
			
			// find the object
			foreach (var entry in m_debugList)
			{
				if(entry.Key.Target == p_object)
				{
					// found it update the info
					entry.Value.updateInfo(p_name, p_info);
					return;
				}
			}
			// did not find it add a new one
			var objectRef = new WeakReference(p_object);
			m_debugList[objectRef] = new DebugInfo(m_form.treeView1.Nodes.Add(p_object.ToString()),
			                                       p_name, p_info);
		}
	}
}
